# _*_ coding: utf-8 _*_
__author__ = 'yinlei'
__date__ = '2018-05-18 8:23'

import hashlib

from wtforms import StringField
from wtforms.validators import regexp, InputRequired

from apps.bases.forms import BaseForm


class SMSCaptchaForm(BaseForm):
    salt = 'fjhfgffxnmytyre45dffhgj'
    telephone = StringField(validators=[regexp(r'^1[345789]\d{9}')])
    timestamp = StringField(validators=[regexp(r'\d{13}')])
    sign = StringField(validators=[InputRequired()])

    def validate(self):
        result = super(SMSCaptchaForm, self).validate()
        if not result:
            return False

        telephone = self.telephone.data
        timestamp = self.timestamp.data
        sign = self.sign.data
        # md5(timestamp+telephone+salt)
        # md5必须要传入一个bytes类型的字符串
        sign2=hashlib.md5((str(timestamp)+telephone+self.salt).encode(encoding='utf-8')).hexdigest()
        if sign==sign2:
            return True
        else:
            return False
